# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggplot2)
library(ggrepel)
library(dplyr)
library(tidyr)
library(tibble)
library(ropls)
library(pROC)
library(egg)
library(purrr)
library(stringr)
library(randomForest)
library(Boruta)
library(magrittr)
library(e1071)
library(optparse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)
diffData <- read.table("../../potential/Sig_Met.txt", header = T, sep = "\t", comment.char = "", stringsAsFactors = F)

diffNames <- diffData %>%
.$Name
data <- read.csv(opt$i, header = T) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    filter(Name %in% diffNames) %>%
    gather("SampleID", "Value", - Name) %>%
    spread(Name, "Value") %>%
    inner_join(sampleInfo, by = c("SampleID")) %>%
    column_to_rownames("SampleID") %>%
    mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
    as.data.frame()

x <- data %>% select(- c("ClassNote"))
y <- data$ClassNote

svmRs <- svm(x, y, type = 'C', kernel = "linear")
unclass(svmRs)
imp <- (t(svmRs$coefs) %*% svmRs$SV)[1,] ^ 2;
names(imp) <- colnames(x);
impData <- imp %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    set_colnames(c("Metabolite", "Value")) %>%
    arrange(Value) %>%
    mutate(Name = factor(Name, levels = unique(Name)))
impData
print(head(impData))

plotData <- impData
outData <- plotData %>%
    arrange(desc(Value)) %>%
    rename(Importance = Value)
outFileName <- paste0(parent, "/SVM_Importance.csv")
write.csv(outData, outFileName, row.names = F)

p <- ggplot(plotData, mapping = aes(x = Value, y = Name)) +
    ylab("") +
    xlab("Importance") +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 10, hjust = 1, vjust = 1), legend.position = 'top',
    legend.text = element_text(size = 9), legend.title = element_text(size = 11), axis.text.y = element_text(size = 10),
    axis.title.y = element_text(size = 11), axis.title.x = element_text(size = 12), panel.grid.major.x = element_blank(),
    panel.border = element_rect(size = 0.75), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_line(
    linetype = 2, color = "#BEBEBE")
    ) +
    geom_point(fill = "blue", shape = 21, color = "blue", size = 3)

pdfFileName <- paste0(parent, "/SVM_Importance.pdf")
ggsave(limitsize = FALSE,pdfFileName, p, width = 6, height = 8)






